package io.github.talelin.latticy.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.github.talelin.autoconfigure.exception.NotFoundException;
import io.github.talelin.latticy.bo.ActivityBO;
import io.github.talelin.latticy.common.mybatis.Page;
import io.github.talelin.latticy.common.util.BeanCopyUtil;
import io.github.talelin.latticy.mapper.ActivityMapper;
import io.github.talelin.latticy.mapper.CouponMapper;
import io.github.talelin.latticy.model.Activity;
import io.github.talelin.latticy.service.ActivityService;
import io.github.talelin.latticy.vo.ActivityDetailVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * activity业务层
 *
 * @author YiHua
 * @date 2021/11/30 5:30 下午
 */
@Service
public class ActivityServiceImpl extends ServiceImpl<ActivityMapper, Activity> implements ActivityService {

     @Autowired
     private CouponMapper couponMapper;              // coupon数据库层

     /**
      * 创建一个activity
      *
      * @param activityBO 活动的入参信息
      */
     @Override
     public void create(ActivityBO activityBO) {
          Activity activity = BeanCopyUtil.copy(activityBO, Activity.class);
          this.save(activity);
     }

     /**
      * 修改activity信息
      *
      * @param activityBO 活动的入参信息
      * @param id         activityId
      */
     @Override
     public void update(ActivityBO activityBO, Integer id) {
          Activity activity = this.getById(id);
          if (activity == null) {
               throw new NotFoundException(90000);
          }
          BeanCopyUtil.copy(activityBO, activity);
          this.updateById(activity);
     }

     /**
      * 获取activity的全部信息,包含activity内部信息
      *
      * @param id activityId
      */
     @Override
     public ActivityDetailVO getDetailById(Integer id) {
          // 校验活动信息是否存在
          Activity activity = this.getById(id);
          if (activity == null) {
               throw new NotFoundException("未找到相关活动", 90000);
          }

          // 查询出在该活动下的优惠券id
          List<Integer> coupons = couponMapper.getCouponsByActivityId(id);

          // 初始化活动详情对象
          ActivityDetailVO activityDetailVO = new ActivityDetailVO();

          // 设置优惠券id
          activityDetailVO.setCouponIds(coupons);

          // 属性拷贝
          BeanCopyUtil.copy(activity, activityDetailVO);

          // 返回活动详细信息
          return activityDetailVO;
     }

     /**
      * 查询多个活动,支持分页
      *
      * @param pageSize false 每页条数
      * @param pageNum  false 当前页
      */
     @Override
     public IPage<Activity> paging(Integer pageNum, Integer pageSize) {
          // 设置分页参数
          Page<Activity> page = new Page<>(pageNum, pageSize);

          // 返回分页后的banner数据集合
          return this.getBaseMapper().selectPage(page, null);
     }
}
